<script setup lang="ts">
import * as monaco from 'monaco-editor'
import EditorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker";
import { onMounted, ref } from 'vue';
import { AgGridVue } from "ag-grid-vue3";
import { AllCommunityModule, ModuleRegistry, themeBalham } from 'ag-grid-community';
ModuleRegistry.registerModules([AllCommunityModule]);

const coreApi = (window as any).coreApi;
console.log(coreApi)
// parse url params
const urlParams = new URLSearchParams(window.location.search);
const params = {
  name: urlParams.get("name") || "",
  path: urlParams.get("path") || "",
  theme: urlParams.get("theme") || "light",
}

// connector methods
const connector = ref({
  name: "",
  id: "",
  url: "",
})
const rowData = ref([
  { make: "Tesla", model: "Model Y", price: 64950, electric: true },
  { make: "Ford", model: "F-Series", price: 33850, electric: false },
  { make: "Toyota", model: "Corolla", price: 29600, electric: false },
]);
const colDefs = ref([
  { field: "make" },
  { field: "model" },
  { field: "price" },
  { field: "electric" }
]);

// query
const handleQuery = (query: string) => {
  coreApi.query({ id: connector.value.id, query: query }).then((res: any) => {
    rowData.value = res.data.items;
    colDefs.value = res.columns.map((column: any) => {
      return { field: column.name }
    })
  })
}
// query all
const handleQueryAll = () => {
  handleQuery(getEditorValue())
}
// create monaco-editor
let editor: monaco.editor.IStandaloneCodeEditor;
const editorId = `editor-${new Date().getTime()}`
onMounted(() => {


  window.parent.postMessage("1111111111111111111111111", "*")
  editor = monaco.editor.create(document.getElementById(editorId) as HTMLElement, {
    value: "",
    automaticLayout: true,
    theme: params.theme == "dark" ? "vs-dark" : "vs",
    language: "sql",
    fontSize: 14,
    lineHeight: 24,
    extraEditorClassName: "",
    minimap: { enabled: false },
    overviewRulerBorder: false,
  });
  editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
    handleSave();
  });
  editor.addAction({
    id: "execute.sql",
    label: `Exec SQL`,
    contextMenuGroupId: "navigation",
    contextMenuOrder: 1,
    run: () => {
      let query = getValueInRange();
      if (!query) {
        query = getEditorValue();
      }
      handleQuery(query);
    },
  });
  editor.addAction({
    id: "save.sql",
    label: `Save SQL`,
    contextMenuGroupId: "navigation",
    contextMenuOrder: 2,
    run: () => {
      handleSave();
    },
  });
})
window.MonacoEnvironment = {
  getWorker() {
    return new EditorWorker();
  },
};

// monaco-editor methods
// set editor value
const setEditorValue = (content: string) => {
  editor.setValue(content.toString());
}

// get editor value
const getEditorValue = () => {
  return (editor as any).getModel().getValue()
}

// get value in range
const getValueInRange = () => {
  return (editor as any).getModel().getValueInRange((editor as any).getSelection());
}
// save/read editor value
const handleSave = () => {
  coreApi.writeFile({ filename: "test.sql", content: getEditorValue() }).then(() => {
    alert("保存成功")
  })
}
const handleRead = () => {
  coreApi.readFile({ filename: "test.sql", content: getEditorValue() }).then((res: string) => {
    setEditorValue(res)
  })
}
const handleTheme = (theme: string) => {
  console.log(theme)
}
// coreApi.listen("handleQueryAll", handleQueryAll)
// coreApi.listen("handleRead", handleRead)
// coreApi.listen("theme", handleTheme)
// coreApi.listen("setValue", setEditorValue)
</script>

<template>
  <div class="fixed w-screen h-screen">
    <div class="vh50" :id="editorId"></div>
    <ag-grid-vue class="vh50" :rowData="rowData" :columnDefs="colDefs" :theme="themeBalham"></ag-grid-vue>
  </div>
</template>

<style scoped></style>
